import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import { getData } from "../mine/function";

const db = wx.cloud.database();
const _ = db.command;

Page({
  data: {
    donorInfo: '',

    showIndex: null,
    active: 0,

    tags_areas: ['全部', '四川', '贵州', '云南', '西藏', '陕西', '甘肃', '青海', '北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '重庆', '宁夏', '新疆', '台湾', '香港', '澳门'],
    selectedIndex_areas: 0,
    tags_age: ['全部', '未读书', '幼儿园', '小学', '中学', '辍学'],
    selectedIndex_age: 0,
    tags_esle: ['全部', '男', '女', '留守', '残疾', '单亲'],
    selectedIndex_else: 0,
    selectedIndex_toDonoteChild: -1,
    selectedIndex_payway: -1,

    selectedIndex_student: -1,


    //new
    searchKeyWord: "",
    studentsShow: [],
    donateMoney: "",
    moneys: [20, 50, 100, 200],
    donateType: "",
    types: ['每月支付', '一次支付'],
    test: "cc,",

    showDialog: false,

  },

  // ---------------------util---------------------
  getLocalDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const formattedDate = `${year}.${month.toString().padStart(2, '0')}.${date.toString().padStart(2, '0')}`;
    return formattedDate;
    // const now = new Date();
    // return now.toLocaleDateString('zh-CN');
  },
  async init() {
    var res = await getData("ourOx68K-yzP1JGUbwnM9FAEJ8hA");
    console.log(res);
    this.setData({
      donorInfo: res,
      donatedChildren: res.students,
    })
    // console.log("donorInfo")
    // console.log(this.data.donorInfo)
  },

  // ---------------------页面跳转孩子信息---------------------
  selectChild(event) {
    var that = this
    console.log("selectChild执行")
    console.log(event.currentTarget.dataset.index)
    var index = event.currentTarget.dataset.index

    wx.navigateTo({
      url: "../child_info/index",
      success: function (res) {
        res.eventChannel.emit('childInfo', { data: that.data.studentsShow[index] })
        console.log("跳转成功")
      },
      fail: function (res) {
        console.log(res);
        console.log("跳转失败")
      }
    })
    // console.log("ok!!")
  },

  // ---------------------搜索模块---------------------
  async onSearch(event) {
    let that = this; // 保存对正确的this的引用

    that.data.searchKeyWord = event.detail ? event.detail : "";
    console.log(that.data.searchKeyWord);

    var searchAddress = that.data.selectedIndex_areas != 0 ? that.data.tags_areas[that.data.selectedIndex_areas] : ""
    var specialCases = that.data.selectedIndex_else != 0 ? that.data.tags_esle[that.data.selectedIndex_else] : ""
    var school = that.data.selectedIndex_age != 0 ? that.data.tags_age[that.data.selectedIndex_age] : ""


    await db.collection('childInfo').where(
      _.and([
        {
          studentName: db.RegExp({
            // regexp: this.data.searchKeyWord,
            regexp: this.data.searchKeyWord,
          }),
        },
        {
          address: db.RegExp({
            regexp: searchAddress,
          }),
        },
        {
          specialCases: db.RegExp({
            regexp: specialCases,
          }),
        },
        {
          school: db.RegExp({
            regexp: school,
          }),
        },
      ])
    ).get({
      success: function (res) {
        console.log("onSearch - 成功");
        console.log(res.data);
        res.data.forEach(function (student) {
          student.descShow = student.description.substring(0, 20) + "..."
        });
        that.setData({  // 使用that来调用setData
          studentsShow: res.data
        });
        // console.log("onSearch - studentsShow");
        // console.log(that.data.studentsShow);
      },
      fail: function (res) {
        console.log("失败");
        console.log(res);
      }
    });


    // var tmpStudent = this.data.studentsShow
    // tmpStudent.forEach(function (student) {
    //   student.descShow = student.description.substring(0, 20) + "..."
    // });
    // console.log("nihao")
    // this.setData({
    //   studentsShow: tmpStudent
    // })
    // console.log("nihao3")
  },

  onTagSearch(event) {
    let that = this; // 保存对正确的this的引用

    var searchAddress = that.data.selectedIndex_areas != 0 ? that.data.tags_areas[that.data.selectedIndex_areas] : ""
    var specialCases = that.data.selectedIndex_else != 0 ? that.data.tags_esle[that.data.selectedIndex_else] : ""
    var school = that.data.selectedIndex_age != 0 ? that.data.tags_age[that.data.selectedIndex_age] : ""

    console.log(searchAddress + " - " + specialCases + " - " + school)

    db.collection('childInfo').where(
      _.and([
        {
          studentName: db.RegExp({
            // regexp: this.data.searchKeyWord,
            regexp: this.data.searchKeyWord,
          }),
        },
        {
          address: db.RegExp({
            regexp: searchAddress,
          }),
        },
        {
          specialCases: db.RegExp({
            regexp: specialCases,
          }),
        },
        {
          school: db.RegExp({
            regexp: school,
          }),
        },
      ])
    ).get({
      success: function (res) {
        console.log("onTagSearch - 成功");
        console.log(res.data);
        that.setData({  // 使用that来调用setData
          studentsShow: res.data
        });
        console.log("onTagSearch - studentsShow");
        console.log(that.data.studentsShow);
      },
      fail: function (res) {
        console.log("失败");
        console.log(res);
      }
    });

  },


  // ---------------------捐款模块---------------------
  // stopPropagation: function (event) {
  //   // 阻止事件冒泡
  //   return false;
  // },
  async confirmPay(event) {
    console.log("确认支付")
    this.data.donateMoney = this.data.moneys[this.data.selectedIndex_toDonoteChild]
    this.data.donateType = this.data.types[this.data.selectedIndex_payway]

    const theChild = this.data.studentsShow[this.data.showIndex]

    // 更新儿童信息的捐款次数
    db.collection('childInfo').where({
      studentName: theChild.studentName
    }).update({
      data: {
        times: theChild.times + 1
      }
    }).then(res => {
      console.log("timesLog")
      console.log(res)
    })
    // console.log("theChild")
    // console.log(theChild)


    // const donorRes = await db.collection('donor').doc('f18e14fa6543438604a4c12e76abaa0f').get();
    // const donorInfo = donorRes.data;
    const donorInfo = this.data.donorInfo;

    var totalDonation = donorInfo.totalDonation || {}; // 如果字段不存在则创建一个空对象
    totalDonation['nov'] = (totalDonation['nov'] || 0) + this.data.donateMoney;

    var donorStudentsRes = await db.collection('donor').doc(donorInfo._id).get();
    var donorStudents = donorStudentsRes.data.students;

    console.log("donorStudents");
    console.log(donorStudents);

    const selectedStudentIndex = donorStudents.findIndex(student => student.name === theChild.studentName);
    if (selectedStudentIndex === -1) {
      console.log("尚未捐助过该学生");

      var newChild = {
        date: this.getLocalDate(),
        imgUrl: theChild.imgUrl,
        name: theChild.studentName,
        province: theChild.province,
        tag: theChild.tag,
        money: this.data.donateMoney,
        times: 1,
      }


      donorStudents.push(newChild);
      db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      this.setData({
        showDialog: true,
      })
    } else {
      console.log("拿到了捐助过的这名学生的信息");
      console.log(donorStudents[selectedStudentIndex])
      donorStudents[selectedStudentIndex].times += 1;
      donorStudents[selectedStudentIndex].money += this.data.donateMoney;

      const updateDonorRes = await db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      console.log(updateDonorRes);

      this.setData({
        showDialog: true,
      })
    }
  },

  // ---------------------前端数据渲染---------------------
  onTagTap_areas(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      selectedIndex_areas: index
    });
    // 处理标签切换的逻辑
    this.onTagSearch(event)
  },
  onTagTap_age(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      selectedIndex_age: index
    });
    // 处理标签切换的逻辑
    this.onTagSearch(event)
  },
  onTagTap_else(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      selectedIndex_else: index
    });
    // 处理标签切换的逻辑
    this.onTagSearch(event)
  },
  onMoneyButtonTap(event) {
    const { index, selected } = event.currentTarget.dataset;
    //console.log(index,selected);
    if (selected) {
      return; // 如果按钮已经选中，则不执行任何操作
    }
    this.setData({
      selectedIndex_toDonoteChild: index
    });
  },
  onPaymentButtonTap(event) {
    const { index } = event.currentTarget.dataset;
    console.log(index);
    this.setData({
      selectedIndex_payway: index
    });
  },


  // ---------------------生命周期---------------------
  onChange(event) {
    // event.detail 的值为当前选中项的索引
    this.setData({ active: event.detail });
  },
  async onShow() {
    this.init()

    try {
      const res = await db.collection('childInfo').where({}).get();
      res.data.forEach(function (student) {
        student.descShow = student.description.substring(0, 20) + "..."
      });
      this.setData({
        studentsShow: res.data
      });
      // console.log("onShow - studentsShow");
      // console.log(this.data.studentsShow);
    } catch (err) {
      console.log("失败");
      console.log(err);
    }
  },

  onLoad() {
    this.init()

    db.collection('childInfo').where({}).get().then(res => {
      res.data.forEach(function (student) {
        student.descShow = student.description.substring(0, 20) + "..."
      });
      this.setData({
        studentsShow: res.data
      });
    }).catch(err => {
      console.log("失败");
      console.log(err);
    });
  },


  // ---------------------其他---------------------
  toChildInfo() {
    wx.navigateTo({
      url: '/pages/child_info/index',
    })
  },
  toSuppliesProjects() {
    wx.navigateTo({
      url: '/pages/suppliesProjects/index',
    })
  },
  // openPopup(e) {
  //   var index = e.currentTarget.dataset.index;
  //   this.setData({
  //     showIndex: index
  //   })
  // },
  closePopup() {
    this.setData({
      showIndex: null
    })
  }
});